import 'dart:async';
import 'dart:io';

import 'package:flu_framework/common/widgets/CustomButton.dart';
import 'package:flu_framework/common/widgets/my_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

class InPayPage extends StatefulWidget {
  const InPayPage({Key? key}) : super(key: key);

  @override
  State<InPayPage> createState() => _InPayPageState();
}

class _InPayPageState extends State<InPayPage> {
  String title = '';
  List<ProductDetails>? _products;
  List<CustomButton> _productButtons = [];
  // 监听更新
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    title = Get.arguments['title'];

    //创建监听:
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        InAppPurchase.instance.purchaseStream;
    // 获得新订阅
    _subscription =
        purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
           _listenToPurchaseUpdated(purchaseDetailsList);
        }, onDone: () {
          _subscription.cancel();
        }, onError: (Object error) {
          // handle error here.
        });

    _getProducts();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(title: title,),
      body: GridView.count(
          crossAxisCount: 3,
          children: _productButtons,
        ),
    );
  }

 _getProducts() async{
   // Set literals require Dart 2.2. Alternatively, use
// `Set<String> _kIds = <String>['product1', 'product2'].toSet()`.
   Set<String> _kIds = <String>{};
   for(int i = 1; i <= 6; i++)
   {
       String productId = 'com.baijiayun.XueDaOnline__' + '$i';
       _kIds.add(productId);
   }

   final ProductDetailsResponse response =
       await InAppPurchase.instance.queryProductDetails(_kIds);
   if (response.notFoundIDs.isNotEmpty) {
     // Handle the error.
   }
   _products = response.productDetails;
   _products!.forEach((element) {
     print("products:${element.title}");
     CustomButton btn = CustomButton(
       title: element.title,
       titleColor: Colors.black,
       positionType:CustomButtonTitleImagePosition.onlyTitle,
       height: 40,
       width: 40,
       backgroundColor: Colors.red,
       onPressed: (ctx,btn){
          int index = _productButtons.indexOf(btn);
          _pay(index);
       },
     );
     _productButtons.add(btn);
   });

   setState(() {

   });

 }


  _pay(int index) async {
    if (_products!.isEmpty) {
      Fluttertoast.showToast(
          msg: 'No item to be paid was found, please try again later'.tr);
      return;
    }
    late PurchaseParam purchaseParam;
    ProductDetails productDetails = _products![index];
    // 两个基础商店以不同方式处理消耗品和非消耗品。如果你使用的是InAppPurchase，需要在这里做区分，为每种类型调用正确的购买方式。

    purchaseParam = PurchaseParam(
        productDetails: productDetails,
      );

      // 购买消耗品
    InAppPurchase.instance.buyConsumable(
          purchaseParam: purchaseParam);

  }


  //商品回调   处理购买更新
  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    //排序
    final sortedList = List.from(purchaseDetailsList);
    sortedList.sort((a, b) => (int.tryParse(b.transactionDate ?? '') ?? 0)
        .compareTo(int.tryParse(a.transactionDate ?? '') ?? 0));
    // 商品列表
    for (final PurchaseDetails purchaseDetails in sortedList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        Fluttertoast.showToast(msg: '请等待支付结果');
        // await writeCache();
        // showLoadingDialog();
      } else {
        //支付错误
        if (purchaseDetails.status == PurchaseStatus.error ||
            purchaseDetails.status == PurchaseStatus.canceled) {
           Fluttertoast.showToast(msg: '${purchaseDetails.error!}');
          // await clearCache();
          // await finishIAPTransaction();
          // hideLoadingDialog();
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          //购买成功  到服务器验证
          Fluttertoast.showToast(msg: '购买成功  到服务器验证');
          // purchaseDetails.billingClientPurchase.originalJson

        }

        if (purchaseDetails.pendingCompletePurchase) {

          await InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    }
  }



}
